package com.ruoyi.system.controller;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.websocket.SignalingHandler;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/videosurveillance")
public class VideoSurveillanceController {
    private final SignalingHandler signalingHandler;

    public VideoSurveillanceController(SignalingHandler signalingHandler) {
        this.signalingHandler = signalingHandler;
    }

    // 获取在线列表（仅 admin 可调用）——前端可展示 role、clientId 列表
    @GetMapping(value = "/online/{token}")
    public List<Map<String, String>> onlineList(@PathVariable String token) {
        System.out.println(token + "请求是否走这里了onlineList: " + signalingHandler.getOnlineClients());
        // TODO: 校验 token 是否为 admin；这里简化演示
        if (!"admin-demo-token".equals(token)) {
            throw new RuntimeException("unauthorized");
        }
        System.out.println("请求是否走这里了onlineList: " + signalingHandler.getOnlineClients());
        return signalingHandler.getOnlineClients();
    }

    // 管理员发起查看请求（平台向 client 下发 start-view）
    @PostMapping("/view")
    public String startView(@RequestBody Map<String, String> requestBody) {
        String clientId = requestBody.get("clientId");
        String token = requestBody.get("token");
        System.out.println(clientId + "请求是否走这里了startView: " + token);
        if (!"admin-demo-token".equals("admin-demo-token")) {
            throw new RuntimeException("unauthorized");
        }
        // 向 client 发送控制命令
        // String payload = "{\"type\":\"control\",\"action\":\"start-view\",\"target\":" + clientId + "}";
        String payload = String.format("{\"type\":\"control\",\"action\":\"start-view\",\"target\":\"%s\",\"requester\":\"%s\"}",
                clientId, "admin-1");
        boolean ok = signalingHandler.sendTo(clientId, payload);
        return ok ? "ok" : "target-offline";
    }
}
